package soap.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import soap.commons.RedisKeys;
import soap.commons.ReleaseRoute;
import soap.utils.JedisTools;

import java.util.List;

/**
 * Created by ZhangPY on 2020/3/12
 * Belong Organization OVERUN-9299
 * overun9299@163.com
 * Explain:
 */
@Component
public class AuthGatewayFilter implements GatewayFilter {

    @Autowired
    private JedisTools jedisTools;

    private AntPathMatcher antPathMatcher =new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        /** 获取request和response，注意：不是HttpServletRequest及HttpServletResponse */
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String value = request.getPath().value();
        if (ReleaseRoute.getAllPath().containsKey(value)) {
            /** 认证通过放行 */
            return chain.filter(exchange);
        }
        for (String key : ReleaseRoute.getAllPath().keySet()) {
            boolean match = antPathMatcher.match(key, value);
            if (match) {
                /** 认证通过放行 */
                return chain.filter(exchange);
            }
        }



        /** 获取所有token */
        List<String> tokens = request.getHeaders().get("token");
        if (tokens != null && tokens.size() > 0) {
            Boolean exists = jedisTools.exists(RedisKeys.LOGIN_INFO + tokens.get(0));
            if (!exists) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            } else {
                /** 重置过期时间 **/
                jedisTools.expire(RedisKeys.LOGIN_INFO + tokens.get(0), 3600);
            }
        } else {
            /** 响应未认证！ */
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            /** 结束请求 */
            return response.setComplete();
        }
        String userInfo = jedisTools.get(RedisKeys.LOGIN_INFO + tokens.get(0));
        exchange.getRequest().mutate().header("userInfo", userInfo).build();

        /** 认证通过放行 */
        return chain.filter(exchange);
    }
}
